package cn.sccdlg.raos.consumer.web;

import cn.sccdlg.raos.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/11/20 23:20
 * 分布式微服务调用
 */
@RestController
@RequestMapping("consumer2")
public class ConsumerController2 {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id) {
        // 根据服务id获取实例
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 从实例中取出ip和端口
        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        String url = "http://" + host + ":" + port + "/user/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }
}
